package com.mall.pay.services;

import com.mall.order.OrderCoreService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.PayOrderSuccessRequest;
import com.mall.order.dto.PayOrderSuccessResponse;
import com.mall.pay.PayCoreService;
import com.mall.pay.constants.PayResultEnum;
import com.mall.pay.constants.PayReturnCodeEnum;
import com.mall.pay.dal.entitys.Payment;
import com.mall.pay.dal.persistence.PaymentMapper;
import com.mall.pay.dto.PayQueryRequest;
import com.mall.pay.dto.PaymentRequest;
import com.mall.pay.dto.alipay.AlipayQueryRetResponse;
import com.mall.pay.dto.alipay.AlipaymentResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.List;

/*
 * @description: 支付核心逻辑
 * @author: mabinbin
 * @date: 2021/8/29
 */
@Service
@Slf4j
public class PayCoreServiceImpl implements PayCoreService {

    @Autowired
    PayHelper payHelper;

    @Autowired
    PaymentMapper paymentMapper;

    @Reference(timeout = 3000, retries = 0, check = false)
    OrderCoreService orderCoreService;

    @Override
    public AlipaymentResponse aliPay(PaymentRequest request) {

        //封装响应参数
        AlipaymentResponse alipaymentResponse = new AlipaymentResponse();

        // 1.  使用支付宝sdk的功能去请求，支付二维码

        try {
            String qrFileName = payHelper.test_trade_precreate(request);

            if (qrFileName == null) {
                // 请求支付二维码失败
                alipaymentResponse.setCode(PayReturnCodeEnum.GET_CODE_FALIED.getCode());
                alipaymentResponse.setMsg(PayReturnCodeEnum.GET_CODE_FALIED.getMsg());
            } else {
                // 否则，请求到支付二维码
                // 2.  在本地插入tb_payment，插入一条本次订单的一条支付记录
                Payment payment = new Payment();
                payment.setStatus(PayResultEnum.PAY_PROCESSING.getCode());
                payment.setOrderId(request.getTradeNo());
                payment.setProductName(request.getSubject());
                // TODO 如果是生产环境，这两条数据需要修改，如果有优惠也需要修改
                payment.setPayerUid(request.getUserId());
                payment.setPayerName("wtgbif9431");
                payment.setPayerAmount(request.getTotalFee());
                payment.setOrderAmount(request.getOrderFee());
                payment.setPayWay(request.getPayChannel());
                payment.setCreateTime(new Date());
                payment.setUpdateTime(new Date());

                //插入到数据库中
                paymentMapper.insert(payment);

                alipaymentResponse.setQrCode(qrFileName);
                alipaymentResponse.setCode(PayReturnCodeEnum.SUCCESS.getCode());
                alipaymentResponse.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());
            }
        } catch (Exception e) {
            log.error("PayCoreServiceImpl.aliPay Occur Exception :" + e);
            alipaymentResponse.setCode(PayReturnCodeEnum.SYSTEM_ERROR.getCode());
            alipaymentResponse.setMsg(PayReturnCodeEnum.SYSTEM_ERROR.getMsg());
        }


        return alipaymentResponse;
    }

    @Override
    public AlipayQueryRetResponse queryAlipayRet(PaymentRequest request) {
        boolean isSuccess = payHelper.test_trade_query(request);
//        boolean isSuccess = true;

        //封装响应参数
        AlipayQueryRetResponse alipayQueryRetResponse = new AlipayQueryRetResponse();

        try {
            if (isSuccess) {
                // 支付成功
                // 1. 修改本订单对应的支付记录： 修改为支付成功
                String orderId = request.getTradeNo();
                Example example = new Example(Payment.class);
                example.createCriteria()
                        .andEqualTo("orderId", orderId);
                List<Payment> payments = paymentMapper.selectByExample(example);
                Payment payment = payments.get(0);
                payment.setUpdateTime(new Date());
                payment.setStatus(PayResultEnum.PAY_SUCCESS.getCode());
                paymentMapper.updateByPrimaryKey(payment);
                // 2. 修改订单状态，为已支付状态
                // 3. 修改订单商品条目，对应的库存状态：3 成功扣减库存
                // 4. 修改库存，将订单中商品对应的库存，锁定库存清零
                PayOrderSuccessRequest payOrderSuccessRequest = new PayOrderSuccessRequest();
                payOrderSuccessRequest.setOrderId(request.getTradeNo());
                orderCoreService.payOrderSuccess(payOrderSuccessRequest);

                alipayQueryRetResponse.setCode(PayReturnCodeEnum.SUCCESS.getCode());
                alipayQueryRetResponse.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());

            } else {
                // 没有成功支付
                // 修改本订单对应的支付记录： 修改为支付失败
                String orderId = request.getTradeNo();
                Example example = new Example(Payment.class);
                example.createCriteria()
                        .andEqualTo("orderId", orderId);
                List<Payment> payments = paymentMapper.selectByExample(example);
                Payment payment = payments.get(0);
                payment.setUpdateTime(new Date());
                payment.setStatus(PayResultEnum.PAY_FAIL.getCode());
                paymentMapper.updateByPrimaryKey(payment);
                alipayQueryRetResponse.setCode(PayReturnCodeEnum.PAYMENT_PROCESSOR_FAILED.getCode());
                alipayQueryRetResponse.setMsg(PayReturnCodeEnum.PAYMENT_PROCESSOR_FAILED.getMsg());
            }
        } catch (Exception e) {
            log.error("PayCoreServiceImpl.queryAlipayRet Occur Exception :" + e);
        }
        return alipayQueryRetResponse;
    }
}
